#include "include/muduo/net/TcpServer.h"
#include "include/muduo/net/EventLoop.h"
#include "include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateServer
{
public:
    TranslateServer(int port)
        : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
                  "TranslateServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::OnConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::OnMessage, this, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));
    }

    // 启动服务器
    void Start()
    {
        _server.start();  // 开始事件的监听
        _baseloop.loop(); // 死循环的事件监控
    }

private:
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        // 新连接建立成功的回调函数
        if (conn->connected())
            std::cout << "连接建立成功\n";
        else
            std::cout << "连接关闭\n";
    }
    std::string Translate(const std::string str)
    {
        std::unordered_map<std::string, std::string> dict = {{"你好", "hello"},
                                                             {"翻译", "translate"},
                                                             {"hello", "你好"},
                                                             {"吃的啥", "内江牛肉面"}};
        auto iter = dict.find(str);
        if (iter == dict.end())
            return "没听懂";
        return dict[str];
    }
    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp)
    {
        // 通信连接接收到请求的回调函数
        // 1.获取客户端发送过来的请求
        std::string req = buffer->retrieveAllAsString();
        // 2.调用translate的接口
        std::string resp = Translate(req);
        // 3.给客户端返回响应
        conn->send(resp);
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer server(8080);
    server.Start();

    return 0;
}